package com.zretc.controller;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.github.pagehelper.PageInfo;
import com.zretc.entity.Orders;
import com.zretc.entity.Refund;
import com.zretc.service.BackOrdersService;
import com.zretc.util.Appliconfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author 周文涛
 * 后端订单管理模块
 */
@Controller
@RequestMapping("back")
public class BackOrdersManagementController {
    @Autowired
    private BackOrdersService backOrdersService;
    private static final Logger LOGGER = LoggerFactory.getLogger(BackOrdersManagementController.class);



    // 获取订单列表
    @GetMapping("orders")
    @ResponseBody
    public PageInfo<Orders> getOrdersList(String filmName,
                                          String ordersId,
                                          String accountName,
                                          String startTime,
                                          String endTime,
                                          @RequestParam("page") String pageNum,
                                          @RequestParam("limit") String pageSize,
                                          String ordersStatus){
        // 组装条件
        Map<String,String> condition = new HashMap<>();
        condition.put("filmName",filmName);
        condition.put("ordersId",ordersId);
        condition.put("accountName",accountName);
        condition.put("startTime",startTime);
        condition.put("endTime",endTime);
        condition.put("pageNum",pageNum);
        condition.put("pageSize",pageSize);
        condition.put("ordersStatus",ordersStatus);
        // 调用业务层
        PageInfo<Orders> pageInfo = backOrdersService.getOrdersList(condition);
        // 返回json数据
        return pageInfo;


    }

    // 获取订单详情
    @GetMapping("orders/{id}")
    @ResponseBody
    public Orders getOrders(@PathVariable("id") String ordersId){
        return  backOrdersService.getOrders(ordersId);
    }


    @GetMapping("refund")
    @ResponseBody
    public PageInfo<Refund> getRefundList(String refundId,
                                          String ordersId,
                                          String accountName,
                                          @RequestParam("page") String pageNum,
                                          @RequestParam("limit") String pageSize,
                                          String startTime,
                                          String endTime,
                                          String refundStatus){
        // 组装条件
        Map<String,String> condition = new HashMap<>();
        condition.put("refundId",refundId);
        condition.put("ordersId",ordersId);
        condition.put("accountName",accountName);
        condition.put("pageSize",pageSize);
        condition.put("pageNum",pageNum);
        condition.put("startTime",startTime);
        condition.put("endTime",endTime);
        condition.put("refundStatus",refundStatus);

        // 调用业务层
        PageInfo<Refund> pageInfo = backOrdersService.getRefundList(condition);
        
        // 返回json数据
        return pageInfo;
    }

    @GetMapping("refund/{id}")
    @ResponseBody
    public Refund getRefund(@PathVariable("id") String refundId){
        return backOrdersService.getRefund(refundId);
    }

    // 同意申请退款
    @PutMapping("refund/{id}")
    @ResponseBody
    public boolean backOp(@PathVariable("id") String refundId){
        boolean flag = false;
        try {
            // 根据退款id获取订单号，退款金额
            Refund refund = backOrdersService.getRefund(refundId);
            String ordersId = refund.getOrders().getOrdersId();
            Float refundPrice = refund.getRefundPrice();

            //获得初始化的AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(Appliconfig.gatewayUrl, Appliconfig.app_id, Appliconfig.merchant_private_key, "json", Appliconfig.charset, Appliconfig.alipay_public_key, Appliconfig.sign_type);
            //设置请求参数
            AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();
            //商户订单号，必填
            String out_trade_no = new String(ordersId);
            //需要退款的金额，该金额不能大于订单金额，必填
            String refund_amount = new String(refundPrice+"");
            //标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传
            String out_request_no = new String(UUID.randomUUID().toString());

            alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                    + "\"refund_amount\":\"" + refund_amount + "\","
                    + "\"out_request_no\":\"" + out_request_no + "\"}");
            //请求
            String result = alipayClient.execute(alipayRequest).getBody();
            flag = backOrdersService.backOrder(refundId);
            LOGGER.debug("=========退款记录：");
            LOGGER.debug("=========退票申请号"+refundId);
            LOGGER.debug("=========订单号："+ordersId);
            LOGGER.debug("=========退款金额："+refundPrice);
            LOGGER.debug("=========退款时间："+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }

        return flag;
    }

}
